package com.roc.web.action.area;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.bean.AreaBean;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.TblInsInf;
import com.roc.service.ServiceException;
import com.roc.service.area.IAreaService;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;
@SuppressWarnings("serial")
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Namespace("/area")
public class AreaAction extends PaginationBaseAction {
	private static final String String = null;
	private Logger logger=LogManager.getLogger(AreaAction.class);
	private AreaSearchCondition searchCondition;
	private AreaBean area;
	
	private List<TblInsInf> orgCodeList = new ArrayList<TblInsInf>();

	@Autowired
	IPageService pagenitionService;
	@Autowired
	IAreaService areaService;


	/**
	 * 初始化区域jsp
	 * @Title: init
	 * @Description:TODO(...)
	 * @see <p></p>
	 * @return
	 * @throws Exception
	 * @author JD
	 * @date: 2017年8月7日 下午3:21:08
	 *
	 */
	@Action(value = "init", results = { @Result(name = "success", location = "/pages/area/queryArea.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })	
	public String init() throws Exception{
		
	       insInf();
			return SUCCESS;
    }

	/**
	 * 查询现有区域
	 * @Title: queryAreaList
	 * @Description:TODO(...)
	 * @see <p></p>
	 * @return
	 * @throws Exception
	 * @author JD
	 * @date: 2017年8月7日 下午3:22:56
	 *
	 */
	@Action(value = "queryArea", results = { @Result(name = "success", location = "/pages/area/queryArea.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String queryArea() throws Exception{
		Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		
		insInf();
		logger.info("查询现有区域开始......");
		try {
			if(searchCondition==null){
				searchCondition=(AreaSearchCondition)getSearchConditionFromSession();
				if(searchCondition==null){
					searchCondition=new AreaSearchCondition();
				}
			}
			if(!op.getRoleType().equals(Role.SYSTEM.getCode())){
				searchCondition.setCode(op.getOrgCode());//当前查询人员所属机构
			}
		
			int rows=pagenitionService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
			}
			List<AreaBean> areaList = new ArrayList<AreaBean>();
			queryAreaList(areaList,searchRsList);
			getRequest().setAttribute("areaList", areaList);
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
			addActionMessage("当前条件下统计到【"+rows+"】条记录");
		} catch (Exception e) {
			
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			return ERROR;
		}		
	   return SUCCESS;
    }
	/**
	 * 查询区域数据
	 * @Title: queryAreaList
	 * @Description:TODO(...)
	 * @see <p></p>
	 * @param blackList
	 * @param searchRsList
	 * @author JD
	 * @date: 2017年8月7日 下午3:24:53
	 *
	 */
	 public  void queryAreaList(List<AreaBean> areaList,List<Object> searchRsList){
		    
			if(searchRsList!=null&&searchRsList.size()>0){
				Iterator iterator=searchRsList.iterator();
				while (iterator.hasNext()) {
					Object[] obj=(Object[]) iterator.next();
					AreaBean bean=new AreaBean();
					bean.setId(Constance.Null2EmptyTrim(obj[0]));
					bean.setName(Constance.Null2EmptyTrim(obj[1]));
					bean.setInsName(Constance.Null2EmptyTrim(obj[2]));
					bean.setStatus(Constance.Null2EmptyTrim(obj[3]));
					bean.setCrtDt(Constance.Null2EmptyTrim(obj[4]));
					bean.setRemark1(Constance.Null2EmptyTrim(obj[5]));//区域编码
					areaList.add(bean);
			}
			
			
		}
	 }
	/**
	 * 初始化添加区域
	 * @Title: addAreajsp
	 * @Description:TODO(...)
	 * @see <p></p>
	 * @return
	 * @author JD
	 * @date: 2017年8月7日 下午3:26:15
	 *
	 */
	@Action(value = "addAreajsp", results = { @Result(name = "success", location = "/pages/area/addArea.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String addAreajsp()
	{
		  insInf();
		area=new AreaBean();
		area.setCrtDt(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

		return SUCCESS;		
	}
	/**
	 * 增加区域
	 * @Title: addBlackList
	 * @Description:TODO(...)
	 * @see <p></p>
	 * @return
	 * @author JD
	 * @throws Exception 
	 * @date: 2017年8月7日 下午3:26:46
	 *
	 */
	@Action(value = "addArea", results = { @Result(name = "success", location = "/pages/area/queryArea.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String addArea() throws Exception
	{
		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
			boolean value =areaService.addAreaList(area, op);
			if(value){
				addActionMessage("添加成功!");
			}else{
				addActionMessage("添加机构下的区域已经存在!");
			}
			queryArea();
		} catch (ServiceException e) {
			e.printStackTrace();
			addActionError("添加区域失败~");
		}
		return SUCCESS;		
	}

	/**
	 * 修改区域页面初始化
	 * @Title: updateAreaJsp
	 * @Description:TODO(...)
	 * @see <p></p>
	 * @return
	 * @author JD
	 * @date: 2017年8月7日 下午3:28:10
	 *
	 */
	@Action(value = "updateAreaJsp", results = { @Result(name = "success", location="/pages/area/addArea.jsp")})
	public String updateAreaJsp()
	{
		try {
			area=areaService.findByAreaNum(area.getId());
		
			area.setId(area.getId());
			area.setInsCode(area.getInsCode());
			area.setName(area.getName());
			area.setInsName(area.getInsName());
			area.setStatus(area.getStatus());
			area.setCrtDt(area.getCrtDt());
			area.setRemark1(area.getRemark1());
			getRequest().setAttribute("flag", "update");
		} catch (ServiceException e) {
			e.printStackTrace();
			e.getMessage();
			addActionError("修改区域页面初始化失败~");
		}
		return SUCCESS;
	}
	/**
	 * 修改区域
	 * @Title: updateStatus
	 * @Description:TODO(...)
	 * @see <p></p>
	 * @return
	 * @author JD
	 * @throws Exception 
	 * @date: 2017年8月7日 下午3:28:57
	 *
	 */
	@Action(value = "updateArea", results = { @Result(name = "success", location="/pages/area/queryArea.jsp")})
	public String updateStatus() throws Exception
	{
		insInf();
		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
			area.setId(area.getId());
			area.setInsCode(area.getInsCode());
			area.setName(area.getName());
			area.setInsName(area.getInsName());
			area.setStatus(area.getStatus());
			area.setCrtDt(area.getCrtDt());
			area.setRemark1(area.getRemark1());
			int c = areaService.updateAreaList(area, op);
			if(c>0){
				addActionMessage("修改成功!");
			}else{
				addActionMessage("修改失败!");
			}
			queryArea();
		} catch (ServiceException e) {
			e.printStackTrace();
			addActionError("更改状态失败~");
		}
		return SUCCESS;
	}
	
	 /**
	  * 验证数据库中区域是否存在
	  * @Title: validateArea
	  * @Description:TODO(...)
	  * @see <p></p>
	  * @author JD
	  * @date: 2017年8月7日 下午3:30:37
	  *
	  */
	@Action(value="validateArea")
	public void validateArea()
	{
		HttpServletResponse response=ServletActionContext.getResponse();
		response.setContentType("text/html;charset=UTF-8");
		try {
			boolean value = areaService.isExistName(area);
			response.getWriter().print(value);
			/*area=areaService.findByAreaNum(area.getId());
			if(area!=null)
			{
				value=false;
			}
			response.getWriter().print(value);*/
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			addActionError("验证区域名称错误!!!");
		} 
	}
	/**
	 * 验证区域下编码是否存在
	 * @Title: valiareaCodeArea
	 * @Description:TODO(...)
	 * @see <p></p>
	 * @author JD
	 * @date: 2017年8月19日 下午3:41:16
	 *
	 */
	@Action(value="valiareaCodeArea")
	public void valiareaCodeArea()
	{
		HttpServletResponse response=ServletActionContext.getResponse();
		response.setContentType("text/html;charset=UTF-8");
		try {
			boolean value = areaService.isExistAreaCode(area);
			response.getWriter().print(value);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			addActionError("验证区域名称错误!!!");
		} 
	}
	/**
     * 初始化机构名称
     * @Title: insInf
     * @Description: TODO
     * @param @return    
     * @return String    
     * @throws
     */
	public String insInf(){
		try {
			  Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			orgCodeList = areaService.queryInsInf( op);
		} catch (Exception e) {
			addActionError("加载机构失败，请联系客服人员");
			logger.error(e.getMessage(),e);
		}
		return SUCCESS;
	}
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {

		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {

		this.setSearchConditionToSubClass(searchCondition);
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {

		getSession().setAttribute(SEARCH_SESSION_TBL_AREA, searchCondition);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {

		return (BaseSearchCondition) getSession().getAttribute(SEARCH_SESSION_TBL_AREA);
	}



	@Override
	protected String getInitPageSize() {

		return Constance.PAGE_MAX_SIZE+"";
	}

	public AreaSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(AreaSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public AreaBean getArea() {
		return area;
	}

	public void setArea(AreaBean area) {
		this.area = area;
	}

	public List<TblInsInf> getOrgCodeList() {
		return orgCodeList;
	}

	public void setOrgCodeList(List<TblInsInf> orgCodeList) {
		this.orgCodeList = orgCodeList;
	}

	


	
}

